<template>
  <el-row :gutter="20">
    <el-col :span="8">
      <el-form-item label="客户：" style="width:70%">
        <el-select placeholder="请选择" v-model="addOtherInfo.organ_id" clearable>
          <el-option v-for="item in supplierList" :key="item.customerid" :label="item.customer"
                :value="item.customerid" />
        </el-select>
      </el-form-item>
    </el-col>
    <el-col :span="8" >
      <el-form-item label="单据日期：">
        <el-date-picker
          v-model="defaultTime"
          type="datetime"
          placeholder="请选择日期"
        />
      </el-form-item>
    </el-col>
    <el-col :span="8">
      <el-form-item label="单据编号：" style="width:70%">
        <el-input v-model="addOtherInfo.number" placeholder="请输入单据编号" />
      </el-form-item>
    </el-col>
  </el-row>

  <div>
    <el-button type="primary" :icon="Plus" @click="addRow" >插入行</el-button>
    <el-button>扫码录入</el-button>
    <el-button>导入明细</el-button>
  </div>
  <div>
    <ul style="overflow: auto;height:25vh;width:90%" >
      <table style="color: black">
        <thead>
          <tr>
            <td><input type="checkbox" /></td>
            <td>仓库名称</td>
            <td>条码</td>
            <td>名称</td>
            <td>规格</td>
            <td>库存</td>
            <td>单位</td>
            <td>数量</td>
            <td>单价</td>
            <td>金额</td>
            <td>备注</td>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in tableData" :key="index">
            <td>
              <input type="checkbox" />
            </td>
            <td>
              <el-select placeholder="请选择仓库" v-model="item.depot_id" style="width:100px"  clearable>
                <el-option v-for="item in warehouseList" :key="item.depot_id" :label="item.depot_name"
              :value="item.depot_id" />
              </el-select>
            </td>
            <td>
              <el-input placeholder="输入条码或名称" v-model="item.bar_code" style="width:70%" />
              <el-button style="width:25%" @click="lookProduct">
                <el-icon style="vertical-align: middle">
                  <Search />
                </el-icon>
              </el-button>
            </td>
            <td>
              <el-input v-model="item.product_name" placeholder="请输入商品名称"/>
            </td>
            <td>
              <el-input v-model="item.standard" />
            </td>
            <td>
              <el-input v-model="item.current_number" />
            </td>
            <td>
              <el-input v-model="item.unit" />
            </td>
            <td>
              <el-input-number style="width:100%" :controls="false" v-model="item.oper_number"
              placeholder="请输入购买数量" />
            </td>
            <td>
              <el-input-number style="width:100%" :controls="false" v-model="item.unit_price"
              placeholder="请输入商品单价" />
            </td>
            <td>
              <el-input-number style="width:100%" :controls="false" v-model="calculatedAmount[index]"
              placeholder="商品总金额" />
            </td>
            <td>
              <el-input v-model="item.remark" />
            </td>
          </tr>
          <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td>{{getNumAndPrice.Num.toFixed(2)}}</td>
            <td>{{getNumAndPrice.Price.toFixed(2)}}</td>
            <td></td>
          </tr>
        </tbody>
      </table>
    </ul>
  </div>
  <div>
    <el-input autosize type="textarea" v-model="addOtherInfo.remark" placeholder="请输入备注"/>
  </div>
  <div  style="float:right;margin-top:50px">
    <el-button type="primary" @click="Save">
      提交
    </el-button>
    <el-button @click="resetForm()">取消</el-button>
  </div>


  <el-dialog v-model="dialogTableVisible" title="商品信息" destroy-on-close style="width: 50%;height:70%">
      <el-row :gutter="20" style="width: 700px;">
          <el-col :span="6">
              <el-form-item label="商品">
              <el-input v-model="form.name" />
              </el-form-item>
          </el-col>
          <el-col :span="6">
              <el-form-item>
              <el-button type="primary" @click="getproductData">查询</el-button>
              </el-form-item>
          </el-col>
      </el-row>
    <el-table :data="productData" style="width: 100%;height:40vh"  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="#" width="55">
      <template v-slot="scope">
        {{ scope.$index + 1 }}  <!-- 自增数字，从1开始 -->
      </template>
    </el-table-column>
      <el-table-column  prop="bar_code" label="条码" />
      <el-table-column  prop="product_name" label="名称" />
      <el-table-column  prop="standard" label="规格" />
      <el-table-column  prop="model" label="型号" />
      <el-table-column  prop="name" label="类别" />
      <el-table-column  prop="unit" label="单位" />
    </el-table>
    <div  style="float:right;margin-top:50px">
    <el-button type="primary" @click="AddProduct">
      提交
    </el-button>
    <el-button @click="ResetProduct">取消</el-button>
  </div>
    <template #footer>
      <div class="dialog-footer">
        <el-pagination
        v-model:current-page="form.PageIndex"
        v-model:page-size="form.PageSize"
        :page-sizes="[10,20,30]"
        layout=" prev, pager, next, sizes"
        :total="1000"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        />
      </div>
    </template>
    <!--分页-->
  <div style="float:right">
      
  </div>
</el-dialog>
</template>

<script lang="ts" setup>
import {reactive,ref,onMounted,computed} from 'vue'
import {useRoute,useRouter} from 'vue-router'
import {ElMessage,ElMessageBox} from 'element-plus'
import moment from 'moment';
import {  Minus, Plus } from '@element-plus/icons-vue';
import {InsertOtherOut } from '@/api/otherwarehousing/index'
import {type OtherOut} from '@/api/otherwarehousing/type'
import {GetProductionBow} from '@/api/production/index'
import {type productionBom} from '@/api/production/type'
import {GetSupplierList, GetWarehouseList } from '@/api/Sales/index'

const router=useRouter()
const route=useRoute()

//供应商列表
const supplierList: any = ref([])
const getSupplierList = async () => {
  await GetSupplierList().then(res => {
      supplierList.value = res.data;
  })
}

//仓库列表
const warehouseList: any = ref([])
const getWarehouseList = async () => {
  await GetWarehouseList().then(res => {
      warehouseList.value = res.data;
  })
}
//子页面
const AddProduct=()=>{
multipleSelection.value.forEach(p=>{
  tableData.value.push(p)
})
dialogTableVisible.value=false
}
const ResetProduct=()=>{
dialogTableVisible.value=false
}

const multipleSelection = ref([])
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val
  console.log(multipleSelection.value)
}

const form=ref<productionBom>({
  name:'',
  categoryid:null,
  PageIndex:1,
  PageSize:10

})
const productData = ref([])
const getproductData = async () => {
await GetProductionBow(form.value)
  .then(res => {
    console.log(res.data.data)
    productData.value = res.data.data
  })
}
const handleSizeChange = (val: number) => {
form.value.PageSize=val;
getproductData()
}
const handleCurrentChange = (val: number) => {
form.value.PageIndex=val;
getproductData()
}
const dialogTableVisible=ref(false)
const lookProduct=()=>{
dialogTableVisible.value=true
}

//主页面
const addOtherInfo=reactive<OtherOut>({
type:'出库',
default_number:'SX'+ moment().format('YYYYMMDDHHmmssSSS'),
number:'SX'+ moment().format('YYYYMMDDHHmmssSSS'),
organ_id:null,
hands_person_id:2,
creator_id:2,
total_price:0,
total_num:0,
remark:'',
file_name:'',
status:true,
link_number:'',
items:[{
  product_id:0,
  bar_code:'',
  product_name:'',
  standard:'',
  model:'',
  color:'',
  product_unit:'',
  oper_number:0,
  unit_price:0,
  all_price:0,
  remark:'',
  depot_id:0,
  another_depot_id:2
}]
})

const Save=async()=>{

addOtheritem()
addOtherInfo.items=addOtherInfo.items.filter(p=>p.product_id!=0)as any
addOtherInfo.total_num=getNumAndPrice.value.Num
addOtherInfo.total_price=getNumAndPrice.value.Price
console.log(addOtherInfo)
await InsertOtherOut(addOtherInfo)
.then(res => {
  if(res.data.code>0){
    ElMessage.success(res.data.message)
    location.reload()
  }else{
    ElMessage.error(res.data.message)
    return
  }
})
}
const resetForm=()=>{
router.push('/StashManagement/StashWarehousing')
}
const defaultTime = ref(new Date())
const tableData = ref([{
  productid:0,
  bar_code:'',
  product_name:'',
  standard:'',
  model:'',
  color:'',
  product_unit:'',
  sku:'',
  oper_number:0,
  unit_price:0,
  all_price:0,
  remark:'',
  depot_id:0,
  another_depot_id:0,
  current_number:0,
  unit:''
}]);
const addOtheritem=()=>{
tableData.value.filter(p=>p.productid!=0).forEach(item=>{
  const newItem = {
       product_id: item.productid,
       bar_code: item.bar_code,
       product_name: item.product_name,
       standard: item.standard,
       model: item.model,
       color: item.color,
       product_unit: item.unit,
       oper_number: item.oper_number,
       unit_price: item.unit_price,
       all_price: item.oper_number * item.unit_price,
       remark: item.remark,
       depot_id: item.depot_id,
       another_depot_id: 2
     };
     addOtherInfo.items.push(newItem);
})
}

const addRow = () => {
tableData.value.push({
  productid:0,
  bar_code:'',
  product_name:'',
  standard:'',
  model:'',
  color:'',
  product_unit:'',
  sku:'',
  oper_number:0,
  unit_price:0,
  all_price:0,
  remark:'',
  depot_id:0,
  another_depot_id:0,
  current_number:0,
  unit:''
});
};

const getNumAndPrice=computed(()=>{
let Num=0
let Price=0
tableData.value.forEach(c=>{
  Num+=c.oper_number*1.0
  Price+=c.oper_number*c.unit_price
})
if(Number.isNaN(Num)){
  Num=0
  Price=0
}
if(Number.isNaN(Price)){
  Num=0
  Price=0
}

return {
  Num:Num,
  Price:Price
}
})

const calculatedAmount=computed(()=>{
    return tableData.value.map(item => {
      return item.oper_number * item.unit_price;
    });
})

onMounted(()=>{
getproductData()
getWarehouseList()
getSupplierList()
})
</script>

<style scoped>
.el-row {
margin-bottom: 20px;
}
.el-row:last-child {
margin-bottom: 0;
}
.el-col {
border-radius: 4px;
}

.grid-content {
border-radius: 4px;
min-height: 36px;
}

</style>